﻿using MediatR;
using PublicCommon;
using T_Rbac.Read.APi.Application.Command.Rules;
using T_Rbac_Demain;
using T_Rbac_Rep.Interface;

namespace T_Rbac.Read.APi.Application.Handlers.RulesHandlers
{
    public class RuleSearchHandler : IRequestHandler<RuleSearchCommand, PageResult<Rule>>
    {
        private readonly IRuleInformation ruleInformation;

        public RuleSearchHandler(IRuleInformation ruleInformation)
        {
            this.ruleInformation = ruleInformation;
        }

        public async Task<PageResult<Rule>> Handle(RuleSearchCommand request, CancellationToken cancellationToken)
        {
             string rname=request.rname;
            var list = await ruleInformation.GetvaluesByResult(x => x.IsDel.Equals(false));
            if(!string.IsNullOrEmpty(rname))
            {
                list = list.Where(x => x.Rname.Contains(rname));
            };
            int Listcount = list.Count();
            int Pagecount = (int)Math.Ceiling(list.Count() * 1.0 / request.pagesize);
            list = list.OrderByDescending(x => x.Rid).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize);
            return new PageResult<Rule>
            {
                TotalCount = Listcount,
                List = list.ToList(),
                PageCount = Pagecount
            };
        }
    }
}
